<?php
if(isset($argv[1])&&$argv[1]=='-d'){
    umask(0);
    if (pcntl_fork() != 0){
            exit();
    }      
    if (pcntl_fork() != 0){
            exit();
    }      
    chdir("/");
}

$server = new Swoole\WebSocket\Server("0.0.0.0", 9502);
$server->on('open', function (Swoole\WebSocket\Server $server, $request){
    //echo "server: handshake success with fd{$request->fd}\n";
});

//全局 
$clientList=array();

$server->on('message', function (Swoole\WebSocket\Server $server, $frame) {
    global $clientList;
    echo "receive from {$frame->fd}:{$frame->data},opcode:{$frame->opcode},fin:{$frame->finish}\n";
    //{"type":"chatMessage","data":{"to_id":0,"to_name":"","content":"99","from_name":"访客250054311","from_id":"250054311","from_avatar":"https://img.52z.com/upload/news/image/20180213/20180213062641_35687.jpg"}}
    $frameData=json_decode($frame->data,true);
    //{"message_type":"chatMessage","data":{"name":"\u5ba2\u670d\u5c0f\u7f8e","avatar":"\/uploads\/20190419\/4eb84234138339f27018e1e3625afd15.jpg","id":"KF2","time":"2020-01-11 14:22:24","content":"\u6d4b"}}
    $sendMsg=array();
    switch($frameData['type']){
        //用户初始化
        case 'userInit':
            $clientList[$frameData['uid']]=$frame->fd;
            $sendMsg=array(
                'message_type' => 'kf_online',
                'data' => array(
                    'kf_name' => '客服小美',
                    'avatar' => 'https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=4217138672,2588039002&fm=26&gp=0.jpg',
                    'kf_id' => 'KF2',
                    'time' => date('Y-m-d H:i:s'),
                    'kf_group'=>1
                )
            );
            $server->push($frame->fd, json_encode($sendMsg));
        break;
        //正常发送消息
        case 'chatMessage':
            $sendMsg=array(
                'message_type' => 'chatMessage',
                'data' => array(
                    'kf_name' => '客服小美',
                    'avatar' => 'https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=4217138672,2588039002&fm=26&gp=0.jpg',
                    'kf_id' => 'KF2',
                    'time' => date('Y-m-d H:i:s'),
                    'content' => htmlspecialchars($frameData['data']['content']),
                )
            );
            if(isset($clientList[$frameData['data']['from_id']])){
                $server->push($clientList[$frameData['data']['from_id']], json_encode($sendMsg));
            }
        break;
        //回应ping
        case 'ping':
            $sendMsg=array("type"=>"pong");
            $server->push($frame->fd, json_encode($sendMsg));
        break;
    }
});

$server->on('close', function ($ser, $fd) {
    //echo "client {$fd} closed\n";
});
$server->start();